package com.dhh.web.modules.user.controller;

import com.dhh.common.utils.Code;
import com.dhh.common.utils.R;
import com.dhh.web.common.shiro.ShiroUtils;
import com.dhh.web.modules.AbstractController;
import com.dhh.web.modules.user.domain.User;
import com.dhh.web.modules.user.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

/**
 * @Auther: dhh
 * @Date: 2018/11/22 15:09
 * @Email: fzlinjianhui@163.com
 * @Description:
 */
@RestController
@RequestMapping("/user/")
public class UserController extends AbstractController {

    @Autowired
    private UserService userService;

    @PostMapping("/save")
    public R save(@Validated User user, BindingResult result){
        if(result.hasErrors()){
            return R.error(result.getAllErrors().get(0).getDefaultMessage());
        }
        if(userService.findByUsername(user.getUsername()).isPresent()){
            return R.error("用户名:"+user.getUsername()+"已存在");
        }
        userService.save(user);
        return R.ok();
    }

    /**
     * 登录
     */
    @RequestMapping(value = "login", method = RequestMethod.POST)
    public R login(String username, String password) {
        try {
            Subject subject = ShiroUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            subject.login(token);
            subject.getSession().getId();
            return R.ok(new HashMap<String,Object>(){{put("token",subject.getSession().getId().toString());}});
        } catch (UnknownAccountException e) {
            return R.error(e.getMessage());
        } catch (IncorrectCredentialsException e) {
            return R.error(Code.BUSINESS_ERROR,"账号或密码不正确");
        } catch (LockedAccountException e) {
            return R.error(Code.BUSINESS_ERROR,"账号已被锁定,请联系管理员");
        } catch (AuthenticationException e) {
            return R.error(Code.BUSINESS_ERROR,"账户验证失败");
        }
    }

    @RequestMapping(value = "login.html")
    public R unLogin(){
        return R.error(Code.UN_LOGIN,"请登录");
    }

    /**
     * 退出
     */
    @RequestMapping(value = "logout", method = RequestMethod.GET)
    public R logout() {
        ShiroUtils.logout();
        return R.ok();
    }
}
